//
//  WBMainViewController.swift
//  赝品微博
//
//  Created by 刘浩林 on 2016/10/31.
//  Copyright © 2016年 刘浩林. All rights reserved.
//

import UIKit
//主控制器
class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()


        //设置代理
        delegate = self

        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLogininNotificiation), object: nil)
        // Do any additional setup after loading the view.
    }
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    /*
     portrait: 竖屏,肖像
     landscape:横屏,风景画
     
     -使用代码控制设备方向,好处:可以在需要横屏的时候单独处理
     -设置支持的方向之后,当前的控制器及子控制器都会遵守这个方向
     -如果播放视频,通常是通过modal展现的
     
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }



    //MARK:-监听方法
    @objc func userLogin(n:Notification){
        print("用户登录通知\(n)")
    }
    //撰写微博
    //撰写按钮
    //FIXME:没有实现
    //private 能够保证方法私有,尽在当前对象访问
    //@objc 允许这个函数在运行时通过OC消息机制被调用
     @objc func composeStatus() -> () {
        print("撰写微博")


        //测试方向旋转

        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nv = UINavigationController(rootViewController: vc)

        present(nv, animated: true, completion: nil)

    }
    //MARK:-私有控件
    //撰写按钮
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}


//MARK:-UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{

    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController description
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        print("将要切换到\(viewController)")

        //1>获取控制器在数组中的索引
       let idx = (childViewControllers as NSArray).index(of: viewController)

        //2>判断当前索引是首页,同时idx也是首页,重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex{
            print("点击首页")
            //3>让表格滚到顶部
            //a)获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc  = nav.childViewControllers[0] as! WBHomeViewController

            vc.tableview?.setContentOffset(CGPoint(x: 0, y: -64),animated: true)

            //4>刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { 
                vc.loadData()
            })


        }


        //判断目标控制器是否是UIViewController

        return !viewController.isMember(of: UIViewController.self)
    }
}

//extension类似于OC中的分类categoary 在swift中还可以用来切分代码块
    //可以吧相近功能的函数,放在一个extension
    //便于代码维护
    //注意:和OC方法也一样,extension不能定义属性
extension WBMainViewController {
     func setupComposeButton(){
        tabBar.addSubview(composeButton)
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width/count - 1
        //CGRectInset 正数向内缩进,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        print("按钮宽度 \(composeButton.bounds.width)")
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)



    }
        //设置所有子控制器
        @objc func setupChildControllers() {

            //0.获取沙盒的json路径
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            //加载 data
            var data = NSData(contentsOfFile: jsonPath)

            if data == nil {
                //从bundle加载data
                let path = Bundle.main.path(forResource: "main.json", ofType: nil)

                data = NSData(contentsOfFile: path!)
            }


            //data一定会有一个内容,反序列化



            //从bundle加载配置 json
            //1.路径 2.加载 NSData 3.反序列化转换成数组
            guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as?[[String: Any]]

                else{
                return
            }



//            //现在很多引用程序中,界面的创建都依赖json
//            let array: [[String: Any]] = [
//                ["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人,回这里看看有什么惊喜"]],
//
//                ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后,别人评论你的微博,发给你的消息,都会在这里收到通知"]],
//
//                ["clsName":"UIViewController"],
//
//                ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后,最新最热微博尽在掌握,不在不会实时潮流擦肩而过"]],
//
//                ["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登陆后,你的微博相册个人资料会在这里显示,展示给别人"]],
//                ]
//
//            //测试数据格式是否正确 - 转换成plist数据更加直观
//            //(array as NSArray).write(toFile: "/Users/liuhaolin/Desktop/demo.plist", atomically: true)
//            //数组 -> json 序列化
//           let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//            (data as NSData).write(toFile: "Users/liuhaolin/Desktop/demo.json", atomically: true)

            //遍历数组,循环创建控制器数组
                var arrayM = [UIViewController]()
            for dict in array! {
                arrayM.append(controller(dict: dict as [String : AnyObject]))
            }
            //设置tabBar 的子控制器
            viewControllers = arrayM




        }

        /// 使用字典创建一个子控制器
        ///
        /// - Parameter dict: 信息字典[clsName,title,imageName,visitorInfo]
        /// - Returns: 子控制器
        private func controller(dict: [String: AnyObject]) -> UIViewController {
            guard   let clsName = dict["clsName"] as? String,
                    let title = dict["title"] as? String,
                    let imageName = dict["imageName"] as? String,
                    let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String:String]
                else {
                return UIViewController()
            }
            //创建视图控制器
            //将clsName转换成cls
            let vc = cls.init()
            vc.title = title

            //设置控制器的访客信息字典
            vc.visitorInfoDictionary = visitorDict

            //设置图像
            vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
            vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)

            //设置tabbar 的标题字体颜色
            vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
            //设置tabbar 的标题字体大小
            vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)


            //实例化导航控制器的时候,会调用push方法
            //将rootVc压栈
            let nav = WBNavigationController(rootViewController: vc)
            return nav




        }
    }

